package com.example.administrator.easycure.FragmentSet;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.administrator.easycure.R;
import com.example.administrator.easycure.activities.DrawerActivity;
import com.example.administrator.easycure.activities.FunctionChooseActivity;
import com.example.administrator.easycure.activities.LocationActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/10/21 0021.
 */

public class FragmentPharmappWhere extends Fragment {

    private DrawerActivity activity;
    private MapView fragment_pharmapp_where_bmv;
    public LocationClient mLocationClient;
    private BaiduMap baiduMap;
    private boolean isFirstLocate = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = (DrawerActivity) getActivity();
        mLocationClient = new LocationClient(activity);
        mLocationClient.registerLocationListener(new MyLocationListener());
        SDKInitializer.initialize(activity.getApplicationContext());

        View view = inflater.inflate(R.layout.fragment_pharmapp_where,container,false);
        init(view);
        baiduMap.setMyLocationEnabled(true);

        return view;
    }

    public void init(View v){

        fragment_pharmapp_where_bmv = (MapView) v.findViewById(R.id.fragment_pharmapp_where_bmv);
        baiduMap = fragment_pharmapp_where_bmv.getMap();
        requestPermission();
    }

    private void navigateTo(BDLocation location) {
        if (isFirstLocate) {
            Toast.makeText(activity, "nav to " + location.getAddrStr(), Toast.LENGTH_SHORT).show();
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
        MyLocationData.Builder locationBuilder = new MyLocationData.
                Builder();
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        MyLocationData locationData = locationBuilder.build();
        baiduMap.setMyLocationData(locationData);
    }

    private void requestPermission(){
        //        申请权限
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String [] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(activity, permissions, 1);
        } else {
            requestLocation();
        }
    }

    private void requestLocation() {
        initLocation();
        mLocationClient.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        fragment_pharmapp_where_bmv.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        fragment_pharmapp_where_bmv.onPause();
    }

    //申请权限第二步
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(activity, "必须同意所有权限才能使用本程序", Toast.LENGTH_SHORT).show();
                            activity.finish();
                            return;
                        }
                    }
                    requestLocation();
                } else {
                    Toast.makeText(activity, "发生未知错误", Toast.LENGTH_SHORT).show();
                    activity.finish();
                }
                break;
            default:
        }
    }

    public class MyLocationListener implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation location) {
        if (location.getLocType() == BDLocation.TypeGpsLocation
                || location.getLocType() == BDLocation.TypeNetWorkLocation) {
            navigateTo(location);
            }
        }
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        fragment_pharmapp_where_bmv.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }
}
